package db

import (
	"errors"
	"log"
	"server_cluster/battle/sharemem"
	"strconv"
	"strings"
)

type Config_captain struct {
	Id    int32  `gorm:"primary_key;column:Id;autoIncrement:false" csv:"Id"`
	Type  int32  `gorm:"column:Type" csv:"Type"`
	Param string `gorm:"column:param" csv:"Param"`
}

func (tmp *Config_captain) TableName() string {
	return "config_captain"
}

func (tmp *Config_captain) getAll() ([]*Config_captain, error) {
	var data []*Config_captain
	result := Conn.Find(&data)
	return data, result.Error
}

func (tmp *Config_captain) LoadData() error {
	data, err := tmp.getAll()
	if err != nil {
		return err
	}
	var myshm = &(sharemem.Myshm.Cfg.Btcpt)
	for key, value := range data {
		if key >= sharemem.BATTLE_CAPTAIN || value.Id <= 0 {
			return errors.New("config_captain format error 1")
		}
		myshm[key].Id = value.Id
		myshm[key].Type = int8(value.Type)
		if len(value.Param) > 0 {
			a_list := strings.Split(value.Param, ";")
			if len(a_list) > sharemem.BATTLE_PARAM_MAX1 {
				return errors.New("config_captain format error 6")
			}
			for k, v := range a_list {
				arg, err := strconv.Atoi(v)
				if err != nil {
					return errors.New("config_captain format error 7")
				}
				myshm[key].Param[k] = int32(arg)
			}
		}
	}
	log.Println("load config_captain completed.")
	return nil
}
